package com.liushuai.eas.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liushuai.eas.common.ExcelUtil;
import com.liushuai.eas.common.MD5Util;
import com.liushuai.eas.common.OriginPsw;
import com.liushuai.eas.common.Result;
import com.liushuai.eas.pojo.Classes;
import com.liushuai.eas.pojo.Department;
import com.liushuai.eas.pojo.Major;
import com.liushuai.eas.pojo.Student;
import com.liushuai.eas.service.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Resource
    private StudentImp studentImp;

    @Resource
    private ClassesImp classesImp;

    @Resource
    private MajorImp majorImp;

    @Resource
    private DepartmentImp departmentImp;

    @Resource
    private ExamImp examImp;

    ExcelUtil excelUtil = new ExcelUtil();

    @PostMapping
    public Result<Student> add(@RequestBody Student student){

        //初始化密码
        student.setPassword(MD5Util.md5(OriginPsw.getOriginPassword()));
        if (studentImp.insert(student)!=1)
            return Result.fail();
        return Result.success(student);
    }

    @PutMapping
    public Result<Student> update(@RequestBody Student student){
        student.setPassword(MD5Util.md5(student.getPassword()));
        if (studentImp.updateById(student)!=0)
            return Result.success(student);
        return Result.fail(student);
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){

        List<Student> studentList;
        int total = 0;
        HashMap<String,Object> map = new HashMap<String,Object>();

        if (search.isEmpty()){
            studentList = studentImp.queryStudentList((pageNum - 1) * pageSize, pageSize);
            total = studentImp.queryTotal();
        }else {
            studentList = studentImp.queryStudentListBySearch((pageNum - 1) * pageSize, pageSize,search);
            total = studentImp.queryTotalBySearch(search);
        }

        for(Student student : studentList){
            if (student.getClassesId()!=null){
                student.setClasses(classesImp.selectOne(student.getClassesId()));
            }
        }

        map.put("records",studentList);
        map.put("total",total);
        map.put("pageSize",pageSize);
        return Result.success("数据加载成功",map);
    }

    @GetMapping("/studentCount")
    public Result<?> studentCount(){
        int total = 0;
        HashMap<String,Object> map = new HashMap<String,Object>();
        total = studentImp.queryTotal();
        map.put("id",0);
        map.put("name","学生人数");
        map.put("icon","el-icon-user-solid");
        map.put("total",total);
        return Result.success("数据加载成功",map);
    }

    @DeleteMapping
    public Result<Student> delete(@RequestBody Student student){
        if (studentImp.deleteById(student)!=1)
            return Result.fail(student);
        return Result.success(student);
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody Student student){
        student.setPassword(MD5Util.md5(student.getPassword()));
        Student stu = studentImp.selectOne(Wrappers.<Student>lambdaQuery().eq(Student::getName, student.getName()).eq(Student::getPassword, student.getPassword()));
        if (stu==null){
            return Result.fail("用户名或密码错误");
        }
        HashMap<Object, Object> map = new HashMap<>();
        stu.setClasses(classesImp.selectOne(stu.getClassesId()));
        map.put("user",stu);
        return Result.success("登录成功，您好！"+stu.getName()+"同学",map);
    }

    @PostMapping("/batchDelete")
    public Result<Student> batchDelete(@RequestBody Map<String,String> map){
        String ids = map.get("ids");
        boolean flag = true;
        String[] id = ids.split(",");
        for (String s : id) {
            if (studentImp.deleteById(Integer.parseInt(s))==0)
                flag = false;
        }

        if (flag)
            return Result.success();
        return Result.fail();
    }

    @PostMapping("/batchResetPsw")
    public Result<Student> batchResetPsw(@RequestBody Map<String,String> map){
        String ids = map.get("ids");
        boolean flag = true;
        String[] id = ids.split(",");
        for (String s : id) {
            Student student = studentImp.queryStudentById(Integer.parseInt(s));
            student.setPassword(MD5Util.md5(OriginPsw.getOriginPassword()));
            if (studentImp.updateById(student)==0)
                flag = false;
        }

        if (flag)
            return Result.success("成功！初始化密码为"+OriginPsw.getOriginPassword());
        return Result.fail();
    }

    @GetMapping("/selectAll")
    public Result<List<Student>> selectAll(){
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        List<Student> studentList = studentImp.selectList(queryWrapper);

        return Result.success(studentList);
    }

    @GetMapping("/exportData")
    public void exportData(@RequestParam String search,
                           @RequestParam Boolean isTemplate,
                           HttpServletResponse response) {
        List<Student> list;
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        if (!search.isEmpty()){
            queryWrapper.like("name",search);
        }
        //需要导出的数据
        list = studentImp.selectList(queryWrapper);

        //设置文件名
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = simpleDateFormat.format(new Date())+"_StudentList.xls";
        if (isTemplate){
            fileName = simpleDateFormat.format(new Date())+"_StudentTemplate.xls";
        }

        //为学生初始专业班级学院
        for (Student student : list) {
            Classes classes = classesImp.selectOne(student.getClassesId());
            Major major = majorImp.selectOne(classes.getMajorId());
            Department department = departmentImp.selectOne(major.getDepartmentId());
            major.setDepartment(department);
            classes.setMajor(major);
            student.setClasses(classes);
        }

        //小标题
        String[] title = {"学号","姓名","性别","所在班级","所在专业","所在学院","出生日期","入学日期","学历","身份"};
        //列宽
        int[] columnWidth = {15,15,15,25,25,25,15,15,15,15};
        //导出
        excelUtil.exportToExcel(fileName,title,columnWidth,list,response,"student",isTemplate);
    }

    @GetMapping("/ratioOfMW")
    public Result<List<Map<String,Object>>> ratioOfMW(){

        List<Map<String,Object>> list = new ArrayList<>();
        HashMap<String, Object> boyMap = new HashMap<>();
        HashMap<String, Object> girlMap = new HashMap<>();
        int boysNum = studentImp.queryBoysNum();
        int girlNum = studentImp.queryGirlNum();
        boyMap.put("value",boysNum);
        boyMap.put("name","男生");
        list.add(0,boyMap);
        girlMap.put("name","女生");
        girlMap.put("value",girlNum);
        list.add(1,girlMap);

        return Result.success(list);
    }

    @GetMapping("/ratioOfMajor")
    public Result<List<Map<Object,Object>>> ratioOfMajor(){

        List<Map<Object, Object>> list = studentImp.queryMajorStudentNum();

        return Result.success(list);
    }

    @PostMapping("/importData")
    public Result<List<Student>> importData(@RequestBody List<Map<String,String>> studentList) throws ParseException {
        ArrayList<Student> insertList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (Map<String, String> map : studentList) {
            Student student = new Student();
            if (!"".equals(map.get("id"))){//有学号 判断是否存在该学员，存在则不插入，否则插入
                if (studentImp.queryStudentById(Integer.parseInt(map.get("id"))) == null) {
                    student.setId(Integer.parseInt(map.get("id")));
                    student.setName(map.get("name"));
                    student.setSex(map.get("sex"));
                    student.setBirthday(sdf.parse(map.get("birthday")));
                    student.setPassword(MD5Util.md5(OriginPsw.getOriginPassword()));
                    student.setClassesId(classesImp.queryClassesByName(map.get("class")).getId());
                    student.setJoinDate(sdf.parse(map.get("joinDate")));
                    studentImp.insert(student);
                    insertList.add(student);
                }
            }else {//无学号 全部插入
                student.setName(map.get("name"));
                student.setSex(map.get("sex"));
                student.setBirthday(sdf.parse(map.get("birthday")));
                student.setPassword(MD5Util.md5(OriginPsw.getOriginPassword()));
                student.setClassesId(classesImp.queryClassesByName(map.get("class")).getId());
                student.setJoinDate(sdf.parse(map.get("joinDate")));
                studentImp.insert(student);
                insertList.add(student);
            }
        }

        return Result.success(insertList);
    }

    @PostMapping(value = "/queryStudentListByClass")
    public Result<List<Map<String,Object>>> queryStudentListByClass(@RequestBody Map<String,String> map){

        int classId = Integer.parseInt(map.get("classId"));
        int courseId = Integer.parseInt(map.get("courseId"));
        String year = map.get("year");

        System.out.println(classId);
        System.out.println(courseId);
        System.out.println(year);

        List<Map<String,Object>> studentList = studentImp.queryStudentListByClass(classId);
        List<Map<String, Object>> examList = examImp.queryExamByClassId(classId);
        for (Map<String,Object> exam : studentList){
            System.out.println(exam);
        }
        for (Map<String,Object> exam : examList){
            System.out.println(exam);
        }
        for (Map<String,Object> student : studentList){
            student.put("studentId",student.get("id"));//设置学生id
            for (Map<String,Object> exam : examList){
                if (String.valueOf(exam.get("student_id")).equals(String.valueOf(student.get("id")))){//有成绩
                    System.out.println("===studentId===:"+student.get("id"));
                    if (String.valueOf(exam.get("course_id")).equals(String.valueOf(courseId))){//有对应课程成绩
                        System.out.println("===courseId===:"+courseId);
                        student.put("score",exam.get("score"));//为对应学生赋值对应课程成绩
                        student.put("id",exam.get("id"));//设置成绩id
                        examList.remove(exam);//移除已赋值成绩
                        break;//赋值完成绩，下一位
                    }
                }
            }
            if (String.valueOf(student.get("studentId")).equals(String.valueOf(student.get("id")))){//遍历完成绩依然没有对应课程成绩
                student.put("id",null);
            }
        }

        System.out.println(studentList);

        return Result.success(studentList);
    }

}
